package ru.bragnikita.utils.swing.widget.form;

import org.apache.commons.lang3.RandomStringUtils;
import ru.bragnikita.utils.swing.message.EventUtils;
import ru.bragnikita.utils.swing.message.SimplePanelMessage;
import ru.bragnikita.utils.swing.widget.CommandWidget;
import ru.bragnikita.utils.swing.widget.Widget;
import ru.bragnikita.utils.swing.widget.common.GuiEventListener;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Nikita.Brazhnikov
 */
public class WidgetController {

	private String objectId;

	public WidgetController() {
		objectId = RandomStringUtils.randomNumeric(6);
	}

	public WidgetController(String objectId) {
		this.objectId = objectId;
	}

	private Map<String, Widget> widgetMap = new LinkedHashMap<>(20);

	public void register(Widget widget) {
		widgetMap.put(widget.getId(), widget);
		if (widget instanceof CommandWidget)
			register((CommandWidget)widget);
	}

	private void register(final CommandWidget commandWidget) {
		commandWidget.addListener(new GuiEventListener<String>() {
			@Override
			public void onEvent(String event) {
				sendActionMessage(commandWidget.getId(), event);
			}
		});
	}

	public ValuesMap getValues() {
		return collectValues(new ValuesMap());
	}

	private ValuesMap collectValues(ValuesMap map) {
		if (map == null)
			map = new ValuesMap();
		for (Map.Entry<String, Widget> entry : widgetMap.entrySet()) {
			Widget widget = entry.getValue();
			if (widget != null)
				map.put(entry.getKey(), widget.getValue());
		}
		return map;
	}

	public void setValues(Map<String, Object> valuesMap) {
		for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
			String key = entry.getKey();
			Widget widget = widgetMap.get(key);
			if (widget != null) {
				widget.setValue(entry.getValue());
			}
		}
	}

	public void sendActionMessage(String sourceId, String actionId) {
		this.sendActionMessage(objectId, sourceId, actionId);
	}

	private void sendActionMessage(String panelId, String sourceId, String actionId) {
		SimplePanelMessage message = new SimplePanelMessage();
		message.setPanelId(panelId);
		message.setSourceId(sourceId);
		message.setActionSourceId(actionId);
		message.setFormParams(collectValues(null));
		EventUtils.publishAcync(message);
	}

}
